using DG.Tweening;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class PromptBox : MonoBehaviour
{

    Image bgImg;
    Text value_tx;

    private void Awake()
    {
        bgImg = transform.Find("bgImg").GetComponent<Image>();
        value_tx = transform.Find("bgImg/value").GetComponent<Text>();
    }

    public void SetValue(string value, float delTime)
    {
        if(this.CalculateLengthOfText(value, value_tx)> Defines.ManualWidth / 2.0f)
        {
            value = $"\t{value}";
        }
        string message = this.StringNewLine(value, value_tx, Defines.ManualWidth / 2.0f);

        RectTransform rtf = value_tx.GetComponent<RectTransform>();
        value_tx.text = message;
        Vector2 vec = GetPreferredSize(rtf.gameObject);
        bgImg.GetComponent<RectTransform>().sizeDelta = vec;

        transform.DOLocalMoveY(transform.localPosition.y + 20, delTime).OnComplete(() =>
        {
            Destroy(gameObject);
        });
    }


    public Vector2 GetPreferredSize(GameObject obj)
    {
        LayoutRebuilder.ForceRebuildLayoutImmediate(obj.GetComponent<RectTransform>());
        return new Vector2(HandleSelfFittingAlongAxis(0, obj), HandleSelfFittingAlongAxis(1, obj));
    }
    private float HandleSelfFittingAlongAxis(int axis, GameObject obj)
    {
        ContentSizeFitter.FitMode fitting = (axis == 0 ? obj.GetComponent<ContentSizeFitter>().horizontalFit : obj.GetComponent<ContentSizeFitter>().verticalFit);
        if (fitting == ContentSizeFitter.FitMode.MinSize)
        {
            return LayoutUtility.GetMinSize(obj.GetComponent<RectTransform>(), axis);
        }
        else
        {
            return LayoutUtility.GetPreferredSize(obj.GetComponent<RectTransform>(), axis);
        }
    }
}
